package formula.web;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

import twork.jsf.util.TworkJsfMessageUtil;
import formula.business.model.Level;
import formula.business.repo.LevelRepository;

@SuppressWarnings("serial")
@ManagedBean
@SessionScoped
public class LevelHome implements Serializable {

	public static final String EL_NAME = "#{levelHome}";
	@ManagedProperty(value = LevelRepository.EL_NAME)
	private LevelRepository levelRepository;
	//
	private Level level;
	private Long levelId;

	/**
	 * All the logic is HERE, it is easier than a Factory Pattern, and reusable
	 */
	public Level getLevel() {
		if (level == null) {
			if ((levelId == null)) {
				level = new Level();
			} else if ((levelId != null) && (level == null)) {
				level = levelRepository.findOne(levelId);
				if (level == null) {
					throw new WebRuntimeException("not.found.by.id", levelId);
				}
			}
		}
		return level;
	}

	public void clear() {
		level = null;
		levelId = null;
	}

	public void doMerge() {
		// the id of level will be null if we are in creation mode
		Long idBeforeMerge = level.getId();
		level = levelRepository.saveAndFlush(level);
		String key = idBeforeMerge == null ? "success.create" : "success.update";
		TworkJsfMessageUtil.addMessageInfo("appMsg", key, Level.class.getSimpleName(), this.level.getName());
		this.level = null;
		this.levelId = null;
	}

	public void doDelete() {
		levelRepository.delete(level);
		//
		TworkJsfMessageUtil.addMessageInfo("appMsg", "success.delete", "Level", this.level.getName());
		this.level = null;
		this.levelId = null;
	}

	public Long getLevelId() {
		return levelId;
	}

	public void setLevelId(Long _levelId) {
		if (_levelId != null) {
			level = null;
			levelId = _levelId;
		}
	}

	public void setLevel(Level level) {
		this.level = level;
	}

	public boolean isLevelEmpty() {
		if (level == null) {
			if ((levelId == null)) {
				return true;
			}
		}
		return false;
	}

	public void setLevelRepository(LevelRepository _levelRepository) {
		levelRepository = _levelRepository;
	}
}
